<?php

require 'lib/password.php';

$stuno = $_POST['stuno'];
$pass = $_POST['pass'];

$query_string = '?';
$error_flag = false;

if(!preg_match("/^\d{12}$/", $stuno)) {
	$query_string = $query_string . "err_stuno=$stuno&";
	$error_flag = true;
}
if(!preg_match("/^.{6,16}$/", $pass)) {
	$query_string = $query_string . 'err_pass=';
	$error_flag = true;
}

if($error_flag) {
	header('Location: login.php' . $query_string);
	die();
}

require 'lib/mysql.php';

$origin = 'select st.sname, st.passwd, se.examed from student as st left join score_exam as se on st.sid = se.sid where st.sid=?';
if(!mysqli_stmt_prepare($mysqli_stmt, $origin)) {
	die('Statement Preparation Fail, Error: (' . mysqli_stmt_errno($mysqli_stmt) . ')' . mysqli_stmt_error($mysqli_stmt));
}

if(!mysqli_stmt_bind_param($mysqli_stmt, 's', $stuno)) {
	die('Statement Binding Param Fail, Error: (' . mysqli_stmt_errno($mysqli_stmt) . ')' . mysqli_stmt_error($mysqli_stmt));
}

if(!mysqli_stmt_execute($mysqli_stmt)) {
	die('Statement Execution Fail, Error: (' . mysqli_stmt_errno($mysqli_stmt) . ')' . mysqli_stmt_error($mysqli_stmt));
}

if(!mysqli_stmt_bind_result($mysqli_stmt, $stuname, $hash_pass, $examed)) {
	die('Statement Result Binding Fail, Error: (' . mysqli_stmt_errno($mysqli_stmt) . ')' . mysqli_stmt_error($mysqli_stmt));
}

if(!mysqli_stmt_store_result($mysqli_stmt)) {
	die('Statement Storing Result Fail, Error: (' . mysqli_stmt_errno($mysqli_stmt) . ')' . mysqli_stmt_error($mysqli_stmt));
}

if(1 != mysqli_stmt_num_rows($mysqli_stmt)) {
	$query_string = $query_string . 'unorpasse=';
	header('Location: login.php');
	die('Statement Wrong Number of Rows, Error: (' . mysqli_stmt_errno($mysqli_stmt) . ')' . mysqli_stmt_error($mysqli_stmt));
}

if(!mysqli_stmt_fetch($mysqli_stmt)) {
	die('Statement Fetching Rows Fail, Error: (' . mysqli_stmt_errno($mysqli_stmt) . ')' . mysqli_stmt_error($mysqli_stmt));
}

if(!password_verify($pass, $hash_pass)) {
	$query_string = $query_string . 'unorpasse=';
	header('Location: login.php');
	die('Password is Wrong.');
}

mysqli_stmt_close($mysqli_stmt);
mysqli_close($mysqli);

session_start();
$_SESSION['sid'] = $stuno;
$_SESSION['sname'] = $stuname;
$_SESSION['examed'] = $examed;
session_write_close();

header('Location: index.php');
?>
